const gulp = require('gulp');
const connect = require("gulp-connect");
const htmlmin = require('gulp-htmlmin');
const cssmin = require('gulp-cssmin');
const sass = require("gulp-sass");
const jsmin = require('gulp-uglify');
const rename = require('gulp-rename');
const sourcemaps = require("gulp-sourcemaps");

gulp.task("server", done => {
    connect.server({
      root: "dist",
      livereload: true
    });
    done();
  });

gulp.task('htmlmin', done => {
    gulp.src('src/html/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('./dist/html'));
    done();
});

gulp.task("sass", done => {
    //将scss文件转换成css，拷贝到dist
    gulp
      .src("src/sass/*.scss")
      .pipe(sourcemaps.init()) //浏览器调试代码时，让浏览器展示的代码和源代码发生关联
      .pipe(sass({ outputStyle: "nested" }))
      .pipe(sourcemaps.write())
      .pipe(cssmin())
      .pipe(gulp.dest("dist/css"))
      .pipe(connect.reload());
    done();
  });

// gulp.task('cssmin', done => {
//     gulp.src('src/style/*.css')
//         .pipe(cssmin())
//         .pipe(gulp.dest('dist/css'));
//     done();
// })


gulp.task('jsmin', done => {
    gulp.src('src/js/*.js')
        // .pipe(jsmin())
        // .pipe(rename(function(path) {
        //     path.extname = ".js";
        // }))
        .pipe(gulp.dest('./dist/js'));
    done();
})

gulp.task('img', done => {
  gulp.src('src/img/*')
      .pipe(gulp.dest('./dist/img'));
  done();
})

gulp.task("watch", done => {
    //实时监听scss和html文件的变化，让源文件和dist目录的文件自动保持一致
    gulp.watch("src/sass/*.scss", gulp.series("sass"));
    gulp.watch("src/js/*.js", gulp.series("jsmin"));
    gulp.watch("src/html/*.html", gulp.series("htmlmin"));
    gulp.watch("src/img/*", gulp.series("img"));
    done();
  });
  
  gulp.task("default", gulp.parallel("server", "watch")); //建立默认任务，同时执行sever和watch两个任务

